﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using WCF.Common.GisService;
using WCF.Common.Navigation;

namespace WCF.Common
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“ObjService”。
    public class ObjService : IObjService
    {
        readonly string UN_DELETE_FLAG = ConfigurationManager.AppSettings["UN_DELETE_FLAG"];
        readonly string TOOLBAR_FLAG = ConfigurationManager.AppSettings["TOOLBAR_FLAG"];
        readonly string KEY_ADMIN = ConfigurationManager.AppSettings["KEY_ADMIN"];

        public void RefreshBuffer()
        {
            ConfigDataBuffer.RefreshBuffer();
        }
        /// <summary>获取登录平台用户标示执行权限对象生成</summary>
        /// <param name="LoginUesrId">用户唯一标示</param>
        /// <returns>权限对象</returns>
        public ConfigObject SetLoginUesr(string LoginUesrId)
        {
            if (LoginUesrId != null)
            {
                return get_qdp_config(LoginUesrId);
            }
            return new ConfigObject() { Message = "参数为空", Success = false };
        }

        bool isAdmin = false;
        public ConfigObject get_qdp_config(string UserId)
        {
            try
            {
                this.RefreshBuffer();

                // 获取专题应用权限清单
                List<RelationRoleApp> AuthApp = new List<RelationRoleApp>();
                List<RelationRoleService> AuthService = new List<RelationRoleService>();
                List<string> roleIDs = new List<string>();

                #region Initialize
                //构造一个QDP平台参数结构对象的实例。
                ConfigObject CO = new ConfigObject()
                {
                    Success = true
                };
                //初始化数据服务资源参数结构情况。
                CO.GisServiceConfig = new GisServiceConfig();
                // 初始化专题应用资源参数结构情况。
                CO.NavigationConfig = new NavigationConfig();
                // 判断是否拥有权限
                isAdmin = true;//CheckUserIsAdmin(UserId);

                roleIDs = (from relation in ConfigDataBuffer.RelationUserRoles
                           where relation.UserID == UserId
                           select relation.RoleID).ToList();

                if (isAdmin == false)
                {
                    // 获取专题应用权限清单
                    AuthApp = (from roleID in roleIDs
                                join role_app in ConfigDataBuffer.RelationRoleApps on roleID equals role_app.RoleID
                                select role_app).Distinct().ToList();
                    // 获取专题服务权限清单
                    AuthService = (from roleID in roleIDs
                                   join role_service in ConfigDataBuffer.RelationRoleServices on roleID equals role_service.RoleID
                                   select role_service).Distinct().ToList();
                }

                #endregion
               
                #region 处理应用
                ConfigDataBuffer.Apps.OrderBy(p => p.Order).ToList().ForEach(app =>
                {
                    if (isAdmin == false && AuthApp.Any(p => p.ID.Equals(app.ID)) == false)
                        return; //无应用访问权限
                    NavDirectory TNavDir, MNavDir;
                    var tags = app.Tags.Split('\\');
                    if (tags.Length < 2) return;
                    string topicName = tags[0];
                    string moduleName = tags[tags.Length - 1];
                    var istool = app.Type != TOOLBAR_FLAG; // 判断组件是否为小工具类型
                    if (istool && CO.NavigationConfig.Parts.Any(p => p.Caption.Equals(topicName)))
                    {
                        TNavDir = CO.NavigationConfig.Parts.First(p => p.Caption.Equals(topicName)) as NavDirectory;
                    }
                    else if (istool == false && CO.NavigationConfig.Tools.Any(p => p.Caption.Equals(topicName)))
                    {
                        TNavDir = CO.NavigationConfig.Tools.First(p => p.Caption.Equals(topicName)) as NavDirectory;
                    }
                    else
                    {
                        TNavDir = new NavDirectory()
                        {
                            Caption = topicName,
                            Code = Guid.NewGuid().ToString(),
                            ParmsExpression = ConfigDataBuffer.GetParameter(topicName)
                        };
                        if (istool)
                        {
                            CO.NavigationConfig.Parts.Add(TNavDir);
                        }
                        else
                        {
                            CO.NavigationConfig.Tools.Add(TNavDir);
                        }
                    }

                    if (TNavDir.SubNotes.Any(p => p.Caption.Equals(moduleName)))
                    {
                        MNavDir = TNavDir.SubNotes.First(p => p.Caption.Equals(moduleName)) as NavDirectory;
                    }
                    else
                    {
                        MNavDir = new NavDirectory()
                        {
                            Caption = moduleName,
                            Code = Guid.NewGuid().ToString(),
                            ParmsExpression = ConfigDataBuffer.GetParameter(moduleName)
                        };
                        TNavDir.SubNotes.Add(MNavDir);
                    }
                    var ANavUis = new NavUISLXap()
                    {
                        Caption = app.Caption,
                        Background = app.Bgc,
                        Code = app.Code,
                        Description = app.Descript,
                        Foreground = app.Frc,
                        ImageUrl1 = app.Icon1,
                        Package = app.URL,
                        ParmsExpression = app.Args,
                        Source = app.Arg1,
                        Type = app.Arg2,
                        Tags = app.Tags
                    };
                    MNavDir.SubNotes.Add(ANavUis);
                });
                #endregion //#region 处理应用
                
                #region 处理服务
                ConfigDataBuffer.Services.OrderBy(p => p.Order).ToList().ForEach(ser =>
                {
                    if (isAdmin == false && AuthService.Any(p => p.ID.Equals(ser.ID)) == false)
                        return; //无应用访问权限

                    var tags = ser.Tags.Split('\\');
                    if (tags.Length < 2) return;
                    string topicName = tags[0];
                    string moduleName = tags[tags.Length - 1];
                    ServiceDirectory TNavDir, MNavDir;
                    // 获取服务专题名称
                    if (CO.GisServiceConfig.MapServices.Any(p => p.Caption.Equals(topicName)))
                    {
                        TNavDir = CO.GisServiceConfig.MapServices.First(p => p.Caption.Equals(topicName)) as ServiceDirectory;
                    }
                    else
                    {
                        TNavDir = new ServiceDirectory()
                        {
                            Caption = topicName
                        };
                        CO.GisServiceConfig.MapServices.Add(TNavDir);
                    }

                    if (TNavDir.SubNotes.Any(p => p.Caption.Equals(moduleName)))
                    {
                        MNavDir = TNavDir.SubNotes.First(p => p.Caption.Equals(moduleName)) as ServiceDirectory;
                    }
                    else
                    {
                        MNavDir = new ServiceDirectory()
                        {
                            Caption = moduleName
                        };
                        TNavDir.SubNotes.Add(MNavDir);
                    }
                    var Layer = new ServiceLayer();

                    Layer.Type = ser.Type;
                    Layer.Code = ser.Code;
                    Layer.Caption = ser.Caption;
                    Layer.Url = ser.URL;
                    Layer.Token = ser.Token;
                    Layer.Description = ser.Descript;
                    Layer.ImageUrl1 = ser.Icon1;
                    Layer.Tags = ser.Tags;
                    Layer.ParmsExpression = ser.Args;
                    MNavDir.SubNotes.Add(Layer);
                });
                #endregion //#region 处理服务
                //CO.GisServiceConfig = new GisServiceConfig();
                return CO;
            }
            catch (Exception ex)
            {
                return new ConfigObject()
                {
                    Success = false,
                    Message = ex.ToString()
                };
            }
        }
       
    }
}